﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using PowerManager.Framework.DataTransfer;
using PowerManager.Framework.ModleBuilder.Attributes;
using PowerManager.Framework.DataPresentation.ExchangeableTarget;
using PowerManager.Framework.DataPresentation.UpdateStrategy;
using System.Net;

namespace PowerManager.Framework.ModleBuilder
{
    internal static class ModelEngine
    {
        internal static void BuildModel(IPAddress ipAddress, IModel model) {
            var properties = model.GetType().GetProperties();
            ProcessPropertiesInfo(ipAddress, properties, model);
        }

        private static void ProcessPropertiesInfo(IPAddress ipAddress, PropertyInfo[] properties, IModel model) {
            foreach (var property in properties) {
                var attributes = Attribute.GetCustomAttributes(property);
                var transferTask = BuildTransferTask(ipAddress, property, model, attributes);
                transferTask.Execute();
            }
        }

        private static TransferTask BuildTransferTask(IPAddress ipAddress, PropertyInfo property, IModel model, Attribute[] attributes) {
            var transferTask = new TransferTask() { 
                Property = property,
                Model = model,
                IpAddress = ipAddress
            };
            foreach (var attribute in attributes) {
                ParseAttribute(transferTask, attribute);
            }

            return transferTask;
        }

        private static void ParseAttribute(TransferTask transferTask, Attribute attribute) {
            if (attribute is SingleAttribute) {
                var sa = (SingleAttribute)attribute;
                transferTask.ExchangeableTarget = new SingleExchangeableTarget(sa.ObjectIdentifier);
            }

            if (attribute is TableAttribute) {
                var ta = (TableAttribute)attribute;
                transferTask.ExchangeableTarget = new TableExchangeableTarget(ta.ObjectIdentifier, ta.Column);
            }

            if (attribute is OneTimeAttribute) {
                transferTask.UpdateStrategy = new OneTimeUpdate();
            }

            if (attribute is TimingAttribute) {
                var ta = (TimingAttribute)attribute;
                transferTask.UpdateStrategy = new TimingUpdate(ta.UpdateInterval);
            }

            if (attribute is AccessControlAttribute) { 
                // TODO: Conside change way to implement.
            }
        }
    }
}
